package utils;

import org.apache.calcite.avatica.org.apache.http.client.utils.URIBuilder;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.*;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.net.HttpURLConnection;
import java.net.URL;


public class HttpUtil {

    public static final String GET_URL = "http://auction.yiyutianxia.com/auction_category/3";


    // 测试接口
    public static final String POST_URL = "http://116.11.122.12:8180/mdserver/service/installLock";

    public static String get() throws Exception {

        HashMap<String, String> cookies = new HashMap<String, String>();
        cookies.put("XSRF-TOKEN", "eyJpdiI6ImFMcTg4bzliVHpRc2x5ZjBRTENJSHc9PSIsInZhbHVlIjoiblFWcUJxcW9UcVhYQnNhdVBXdTY3YWcxdFV1VlBKT3VPaHhUU3p5Vm9HZ1VGaHVqMVpoNXpLWkZcL3lvOE5lSmkiLCJtYWMiOiJiMDZlMjkxYjZiNmYyMmMxNTc1ZmE1NTU3ODE1ZDk0N2NhOTk1MjZhYjVkNzg5OWM2ODA1ZTQ2MGVmZTljOTBmIn0%3D");
        cookies.put("_session", "eyJpdiI6Ik1JaVpDcVcybU9ZRkl1OU9cL3A4djdBPT0iLCJ2YWx1ZSI6IjIxXC9zTFZxb0lIYWNvOURsS3dEa1NrVlF1b0h6dVpDa1VsZTRQQ1JcL1oxNXdFM0VrekthOTNmZHdvMExpcVwvRnoiLCJtYWMiOiIwZTNiZmQ3MTg3YmJjN2JjNmNlM2U1YWNiNmQ5N2Y5N2RhZmU2YWNmZTdlYmRhZDVhZjZjNGVhNTllNjE3NjFiIn0%3D");
        cookies.put("Hm_lvt_4e160735f0485252c7e885edaed311af", "1603717349");
        cookies.put("Hm_lpvt_4e160735f0485252c7e885edaed311af", "1603797129");

        BasicCookieStore cookieStore = new BasicCookieStore();
        for (String cookie : cookies.keySet()) {
            BasicClientCookie cur = new BasicClientCookie(cookie, cookies.get(cookie));
            cur.setPath("/");
            cur.setExpiryDate(new Date(System.currentTimeMillis() + 60 * 60 * 1000));
            cookieStore.addCookie(cur);
        }

        HttpClient client = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
        final HttpGet request = new HttpGet(GET_URL);

        //設置httpGet的头部參數信息

        request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3");

        request.setHeader("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");

        request.setHeader("Accept-Encoding", "gzip, deflate");

        request.setHeader("Accept-Language", "zh-cn,zh;q=0.5");

        request.setHeader("Connection", "keep-alive");

        request.setHeader("Host", "www.cnblogs.com");

        request.setHeader("refer", "http://www.baidu.com/s?tn=monline_5_dg&bs=httpclient4+MultiThreadedHttpConnectionManager");

        request.setHeader("User-Agent", "Mozilla/5.0 (Linux; Android 9; Redmi Note 5 Build/PKQ1.180904.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/77.0.3865.120 MQQBrowser/6.2 TBS/045410 Mobile Safari/537.36 MMWEBID/220 MicroMessenger/7.0.10.1560(0x27000A30) Process/tools NetType/WIFI Language/zh_CN ABI/arm64");

        HttpResponse response = client.execute(request);
        return response.toString();
    }


    /**
     * 接口调用 GET
     */
    public static void httpURLConectionGET() {
        try {
            URL url = new URL(GET_URL);    //把字符串转换为URL请求地址
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打开连接
            //addRequestProperty添加相同的key不会覆盖，如果相同，内容会以{name1,name2}
            connection.addRequestProperty("from", "sfzh");  //来源哪个系统
            //setRequestProperty添加相同的key会覆盖value信息
            //setRequestProperty方法，如果key存在，则覆盖；不存在，直接添加。
            //addRequestProperty方法，不管key存在不存在，直接添加。
            connection.setRequestProperty("user", "user");  //访问申请用户
            InetAddress address = InetAddress.getLocalHost();
            String ip = address.getHostAddress();//获得本机IP
            connection.setRequestProperty("ip", ip);  //请求来源IP
            connection.setRequestProperty("encry", "00000");
            //connection.setRequestProperty("设置请求头key", "请求头value");


            connection.connect();// 连接会话
            // 获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {// 循环读取流
                sb.append(line);
            }
            br.close();// 关闭流
            connection.disconnect();// 断开连接
            System.out.println(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("失败!");
        }
    }

    /**
     * 接口调用  POST
     */
    public static void httpURLConnectionPOST() {
        try {
            //传递参数
            String Parma = "?cardType={}&cardID={}";

            URL url = new URL(POST_URL);
            // 将url 以 open方法返回的urlConnection  连接强转为HttpURLConnection连接  (标识一个url所引用的远程对象连接)
            // 此时cnnection只是为一个连接对象,待连接中
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置连接输出流为true,默认false (post 请求是以流的方式隐式的传递参数)
            connection.setDoOutput(true);
            // 设置连接输入流为true
            connection.setDoInput(true);
            // 设置请求方式为post
            connection.setRequestMethod("POST");
            // post请求缓存设为false
            connection.setUseCaches(false);
            // 设置该HttpURLConnection实例是否自动执行重定向
            connection.setInstanceFollowRedirects(true);
            // 设置请求头里面的各个属性 (以下为设置内容的类型,设置为经过urlEncoded编码过的from参数)
            // application/x-javascript text/xml->xml数据 application/x-javascript->json对象 application/x-www-form-urlencoded->表单数据
            // ;charset=utf-8 必须要，不然妙兜那边会出现乱码【★★★★★】
            //addRequestProperty添加相同的key不会覆盖，如果相同，内容会以{name1,name2}
            connection.addRequestProperty("from", "sfzh");  //来源哪个系统
            //setRequestProperty添加相同的key会覆盖value信息
            //setRequestProperty方法，如果key存在，则覆盖；不存在，直接添加。
            //addRequestProperty方法，不管key存在不存在，直接添加。
            connection.setRequestProperty("user", "user");  //访问申请用户
            InetAddress address = InetAddress.getLocalHost();
            String ip = address.getHostAddress();//获得本机IP
            connection.setRequestProperty("ip", ip);  //请求来源IP
            connection.setRequestProperty("encry", "123456");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            // 建立连接 (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)
            connection.connect();
            // 创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容)
            DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());
            // 格式 parm = aaa=111&bbb=222&ccc=333&ddd=444
            String parm = "username=zhagnsan&password=0000";
            System.out.println("传递参数：" + parm);
            // 将参数输出到连接
            dataout.writeBytes(parm);
            // 输出完成后刷新并关闭流
            dataout.flush();
            dataout.close(); // 重要且易忽略步骤 (关闭流,切记!)
            //System.out.println(connection.getResponseCode());
            // 连接发起请求,处理服务器响应  (从连接获取到输入流并包装为bufferedReader)
            BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            StringBuilder sb = new StringBuilder(); // 用来存储响应数据

            // 循环读取流,若不到结尾处
            while ((line = bf.readLine()) != null) {
//sb.append(bf.readLine());
                sb.append(line).append(System.getProperty("line.separator"));
            }
            bf.close();    // 重要且易忽略步骤 (关闭流,切记!)
            connection.disconnect(); // 销毁连接
            System.out.println(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // HTTP POST请求, 将json当做一个字符串传入httppost的请求体
    public static String sendPost(String host, String requestPath, Map<String, String> requestBody) throws Exception {
        HttpClient client = HttpClients.createDefault();
        URIBuilder builder = new URIBuilder();
        try {
            URI uri = builder.setScheme("http")
                    .setHost(host)
                    .setPath(requestPath)
                    .build();

            HttpPost post = new HttpPost(uri);
            //设置请求头
            post.setHeader("Content-Type", "application/json");
            //设置请求体
            post.setEntity(new StringEntity(JsonUtil.writeValueAsString(requestBody)));
            //获取返回信息
            HttpResponse response = client.execute(post);

            //按指定编码转换结果实体为String类型
            if (200 == response.getStatusLine().getStatusCode()) {
                String respBody = EntityUtils.toString(response.getEntity(), "utf-8");
//                System.out.println(respBody);
                return respBody;
            }
        } catch (Exception e) {
            System.out.println("接口请求失败: " + e.getMessage());
        }
        return "fail";
    }

    public static void main(String[] args) throws Exception {
        Map<String, String> requestBody = new HashMap<>();
        requestBody.put("brandName", "brand_abc_02");
        final String result = sendPost("local.coupangdev.com:8080", "/api/v1/getSellerInfoByBrandName", requestBody);
        System.out.println("current response: " + result);
    }

}


